package Midium;

// 64.最小路径和
// 思路：和62题、63题思路基本相同
// dp[i][j] = Min(dp[i-1][j],dp[i][j-1])+grid[i][j]
public class Solution64 {
    public static int minPathSum(int[][] grid) {
        int dp[][] = new int[grid.length][grid[0].length];
        int x, y;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                try {
                    x = dp[i][j - 1];
                } catch (Exception e) {
                    x = -1;
                }
                try {
                    y = dp[i - 1][j];
                } catch (Exception e) {
                    y = -1;
                }
                if (x == -1 && y == -1) {
                    dp[i][j] = grid[i][j];
                } else if (x == -1) {
                    dp[i][j] = y + grid[i][j];
                } else if (y == -1) {
                    dp[i][j] = x + grid[i][j];
                } else {
                    dp[i][j] = Math.min(x, y) + grid[i][j];
                }
            }
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }

    public static void main(String[] args) {
        int[][] grid = new int[][]{{1, 3, 1}, {1, 5, 1}, {4, 2, 1}};
        int i = minPathSum(grid);
        System.out.println(i);
    }
}
